import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { IPaginationFormWithCondition } from 'types/requestParams';
import { InjectModel } from 'nest-typegoose';
import { ReturnModelType } from '@typegoose/typegoose';
import { Swiper } from '@libs/db/models/swiper.model';
import { SiteInfo } from '@libs/db/models/site-info.model';
import { CompanyInfo } from '@libs/db/models/company-info.model';
import { EmailConfig } from '@libs/db/models/email-config.model';
import { formatAgragateCondition } from 'utils';


@Injectable()
export class ConfigurationService {
  constructor(
    @InjectModel(Swiper) private readonly swiperModel: ReturnModelType<typeof Swiper>,
    @InjectModel(SiteInfo) private readonly siteInfoModel: ReturnModelType<typeof SiteInfo>,
    @InjectModel(CompanyInfo) private readonly companyInfoModel: ReturnModelType<typeof CompanyInfo>,
    @InjectModel(EmailConfig) private readonly emailConfigModel: ReturnModelType<typeof EmailConfig>
  ) { }

  async create(body: Swiper) {
    try {
      const swipersCount = await this.swiperModel.find({ isShow: 1 }).count();
      if (swipersCount >= 5) {
        throw new HttpException('展示的轮播数量同时超过5个，不允许新增', HttpStatus.BAD_REQUEST)
      } else {
        const doc = await this.swiperModel.create(body)
        await doc.save()
        return '新增成功'
      }
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  async findAll(body: IPaginationFormWithCondition) {
    try {
      const condition = [
        {
          $match: {
            $and: [{ name: { $regex: body.name ?? '' } }]
          }
        },
        {
          $sort: { order: 1 }
        },
        {
          $facet: {
            total: [{ $count: 'count' }],
            rows: [{ $skip: (body.pageNum - 1) * body.pageSize }, { $limit: body.pageSize }, { $project: { __v: 0 } }]
          }
        },
        {
          $project: {
            rows: "$rows",
            total: { $arrayElemAt: ["$total.count", 0] },
          }
        }
      ]
      // @ts-ignore
      const res = await this.swiperModel.aggregate(condition)
      if (res[0]) {
        return res[0]
      } else {
        return {}
      }
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  // 获取已发布的首页轮播图
  async getPublished() {
    try {
      const res = await this.swiperModel.find({}).sort({ order: 1 })
      return res
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  async findOne(id: number) {
    try {
      return 'ok'
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  async update(body: Swiper) {
    try {
      await this.swiperModel.findByIdAndUpdate(body._id, body).exec()
      return '更新成功'
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  async remove(id: number) {
    try {
      await this.swiperModel.findByIdAndDelete(id)
      return 'ok'
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }


  // ========== 站点信息相关方法 ==========

  /**
   * 创建站点信息
   * @param body 站点信息数据，来源于请求体
   * @returns 创建的站点信息
   */
  async createSiteInfo(body: SiteInfo) {
    try {
      console.log(body, '参数');

      const doc = await this.siteInfoModel.create(body);
      return doc.toObject();
    } catch (e) {
      throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 获取站点信息（只有一条数据）
   * @returns 站点信息详情
   */
  async getSiteInfo() {
    try {
      const siteInfo = await this.siteInfoModel.findOne().exec();
      if (!siteInfo) {
        return null;
      }
      return siteInfo;
    } catch (error) {
      throw new Error(`获取站点信息失败: ${error.message}`);
    }
  }

  /**
   * 更新站点信息
   * @param id 站点信息ID，来源于路径参数
   * @param body 更新的站点信息数据，来源于请求体
   * @returns 更新结果消息
   */
  async updateSiteInfo(id: string, body: Partial<SiteInfo>) {
    try {
      const existingSiteInfo = await this.siteInfoModel.findById(id);
      if (!existingSiteInfo) {
        throw new HttpException('站点信息不存在', HttpStatus.NOT_FOUND);
      }

      await this.siteInfoModel.findByIdAndUpdate(id, body, { new: true });
      return '站点信息更新成功';
    } catch (e) {
      if (e.status === 404) {
        throw new HttpException(e.message || e, e.status);
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
  }

  /**
   * 删除站点信息
   * @param id 站点信息ID，来源于路径参数
   * @returns 删除结果消息
   */
  async removeSiteInfo(id: string) {
    try {
      const siteInfo = await this.siteInfoModel.findById(id);
      if (!siteInfo) {
        throw new HttpException('站点信息不存在', HttpStatus.NOT_FOUND);
      }

      await this.siteInfoModel.findByIdAndDelete(id);
      return '站点信息删除成功';
    } catch (e) {
      if (e.status === 404) {
        throw new HttpException(e.message || e, e.status);
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
  }

  // ========== 公司信息相关方法 ==========

  /**
   * 创建公司信息
   * @param body 公司信息数据，来源于请求体
   * @returns 创建的公司信息
   */
  async createCompanyInfo(body: CompanyInfo) {
    try {
      const doc = await this.companyInfoModel.create(body);
      return doc.toObject();
    } catch (e) {
      throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 获取公司信息（只有一条数据）
   * @returns 公司信息详情
   */
  async getCompanyInfo() {
    try {
      const companyInfo = await this.companyInfoModel.findOne().exec();
      if (!companyInfo) {
        return {}
      }
      return companyInfo;
    } catch (error) {
      throw new Error(`获取公司信息失败: ${error.message}`);
    }
  }

  /**
   * 更新公司信息
   * @param id 公司信息ID，来源于路径参数
   * @param body 更新的公司信息数据，来源于请求体
   * @returns 更新结果消息
   */
  async updateCompanyInfo(id: string, body: Partial<CompanyInfo>) {
    try {
      const existingCompanyInfo = await this.companyInfoModel.findById(id);
      if (!existingCompanyInfo) {
        throw new HttpException('公司信息不存在', HttpStatus.NOT_FOUND);
      }

      await this.companyInfoModel.findByIdAndUpdate(id, body, { new: true });
      return '公司信息更新成功';
    } catch (e) {
      if (e.status === 404) {
        throw new HttpException(e.message || e, e.status);
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
  }

  /**
   * 删除公司信息
   * @param id 公司信息ID，来源于路径参数
   * @returns 删除结果消息
   */
  async removeCompanyInfo(id: string) {
    try {
      const companyInfo = await this.companyInfoModel.findById(id);
      if (!companyInfo) {
        throw new HttpException('公司信息不存在', HttpStatus.NOT_FOUND);
      }

      await this.companyInfoModel.findByIdAndDelete(id);
      return '公司信息删除成功';
    } catch (e) {
      if (e.status === 404) {
        throw new HttpException(e.message || e, e.status);
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR);
      }
    }
  }

  /**
   * 获取站点和公司信息的组合数据
   * @returns 包含站点信息和公司信息的对象
   */
  async getSiteAndCompanyInfo(): Promise<{ siteInfo: any; companyInfo: any }> {
    try {
      const [siteInfo, companyInfo] = await Promise.all([
        this.getSiteInfo(),
        this.getCompanyInfo()
      ]);

      return {
        siteInfo,
        companyInfo
      };
    } catch (error) {
      console.error('获取站点和公司信息失败:', error);
      throw new HttpException(
        `获取站点和公司信息失败: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  /**
   * 获取系统配置信息
   * @returns 系统配置对象
   */
  async getSystemConfig() {
    return {
      siteInfo: {
        siteTemplate: "default"
      }
    };
  }

  // ========== 邮件配置相关方法 ==========

  /**
   * 创建邮件配置
   * @param body 邮件配置数据
   * @returns 创建的邮件配置
   */
  async createEmailConfig(body: EmailConfig) {
    try {
      console.log(body, 'body');
      const doc = await this.emailConfigModel.create({
        ...body,
        createdAt: new Date(),
        updatedAt: new Date()
      });
      await doc.save();
      return doc;
    } catch (e) {
      console.error('创建邮件配置失败:', e);
      throw new HttpException('创建邮件配置失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 获取所有邮件配置
   * @returns 邮件配置列表
   */
  async getAllEmailConfigs() {
    try {
      return await this.emailConfigModel.find().sort({ createdAt: -1 });
    } catch (e) {
      console.error('获取邮件配置列表失败:', e);
      throw new HttpException('获取邮件配置列表失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 获取活跃的邮件配置
   * @returns 活跃的邮件配置
   */
  async getActiveEmailConfig() {
    try {
      const config = await this.emailConfigModel.findOne({ isActive: true });
      if (!config) {
        // 如果没有活跃配置，返回默认配置
        return {
          emailName: '客户留言系统',
          emailHost: 'smtp.qq.com',
          emailPort: 587,
          emailSecure: false,
          emailUser: '2735332396@qq.com',
          emailPassword: 'rkmxxazafyebdgdb',
          emailFromName: '客户留言系统',
          emailFromAddress: '2735332396@qq.com',
          emailToAddress: 'hrkes01@163.com',
          emailToName: 'ToName',
        };
      }
      return config;
    } catch (e) {
      console.error('获取活跃邮件配置失败:', e);
      throw new HttpException('获取活跃邮件配置失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 根据ID获取邮件配置
   * @param id 邮件配置ID
   * @returns 邮件配置详情
   */
  async getEmailConfigById(id: string) {
    try {
      const config = await this.emailConfigModel.findById(id);
      if (!config) {
        throw new HttpException('邮件配置不存在', HttpStatus.NOT_FOUND);
      }
      return config;
    } catch (e) {
      if (e.status === 404) {
        throw e;
      }
      console.error('获取邮件配置详情失败:', e);
      throw new HttpException('获取邮件配置详情失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 更新邮件配置
   * @param id 邮件配置ID
   * @param body 更新的邮件配置数据
   * @returns 更新结果消息
   */
  async updateEmailConfig(id: string, body: Partial<EmailConfig>) {
    try {
      const config = await this.emailConfigModel.findById(id);
      if (!config) {
        throw new HttpException('邮件配置不存在', HttpStatus.NOT_FOUND);
      }

      // 如果将此配置设为活跃，则将其他配置设为非活跃
      if (body.isActive && !config.isActive) {
        await this.emailConfigModel.updateMany({ isActive: true }, { isActive: false });
      }

      await this.emailConfigModel.findByIdAndUpdate(id, {
        ...body,
        updatedAt: new Date()
      });

      return '邮件配置更新成功';
    } catch (e) {
      if (e.status === 404) {
        throw e;
      }
      console.error('更新邮件配置失败:', e);
      throw new HttpException('更新邮件配置失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 删除邮件配置
   * @param id 邮件配置ID
   * @returns 删除结果消息
   */
  async removeEmailConfig(id: string) {
    try {
      const config = await this.emailConfigModel.findById(id);
      if (!config) {
        throw new HttpException('邮件配置不存在', HttpStatus.NOT_FOUND);
      }

      await this.emailConfigModel.findByIdAndDelete(id);
      return '邮件配置删除成功';
    } catch (e) {
      if (e.status === 404) {
        throw e;
      }
      console.error('删除邮件配置失败:', e);
      throw new HttpException('删除邮件配置失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  /**
   * 激活指定的邮件配置
   * @param id 邮件配置ID
   * @returns 激活结果消息
   */
  async activateEmailConfig(id: string) {
    try {
      const config = await this.emailConfigModel.findById(id);
      if (!config) {
        throw new HttpException('邮件配置不存在', HttpStatus.NOT_FOUND);
      }

      // 将所有配置设为非活跃
      await this.emailConfigModel.updateMany({}, { isActive: false });

      // 激活指定配置
      await this.emailConfigModel.findByIdAndUpdate(id, {
        isActive: true,
        updatedAt: new Date()
      });

      return '邮件配置激活成功';
    } catch (e) {
      if (e.status === 404) {
        throw e;
      }
      console.error('激活邮件配置失败:', e);
      throw new HttpException('激活邮件配置失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}

